/**
 * 预约管理页面JavaScript逻辑
 */

let currentMode = 'all'; // all, overdue
let vaccineList = [];
let siteList = [];
let personList = [];

function normalizeAppointmentList(data) {
    if (!data) {
        return [];
    }
    if (Array.isArray(data)) {
        return data;
    }
    if (Array.isArray(data.records)) {
        return data.records;
    }
    return [];
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    if (!Auth.isLoggedIn()) {
        window.location.href = '../login.html';
        return;
    }

    // 检查用户角色
    if (!Auth.checkRole(UserRole.NORMAL_USER)) {
        UI.showMessage('您没有权限访问此页面', 'danger');
        setTimeout(() => {
            Auth.logout();
        }, 2000);
        return;
    }

    // 初始化页面
    init();
});

/**
 * 初始化页面
 */
async function init() {
    // 显示用户信息
    displayUserInfo();
    
    // 加载预约列表
    await loadAllAppointments();
    
    // 设置默认预约时间为明天
    setDefaultAppointmentTime();
}

/**
 * 显示用户信息
 */
function displayUserInfo() {
    const userInfo = Auth.getUserInfo();
    if (userInfo) {
        const userName = userInfo.account || '用户';
        document.getElementById('userName').textContent = userName;
        
        // 设置头像首字母
        const avatar = document.getElementById('userAvatar');
        avatar.textContent = userName.charAt(0).toUpperCase();
    }
}

/**
 * 加载全部预约
 */
async function loadAllAppointments() {
    currentMode = 'all';
    document.getElementById('listTitle').textContent = '我的预约';
    
    try {
        const pageData = await HttpClient.get('/appointment/list');
        const appointments = normalizeAppointmentList(pageData);
        displayAppointments(appointments);
    } catch (error) {
        console.error('加载预约列表失败:', error);
        UI.showMessage('加载预约列表失败', 'danger');
    }
}

/**
 * 加载逾期预约
 */
async function loadOverdueAppointments() {
    currentMode = 'overdue';
    document.getElementById('listTitle').textContent = '逾期预约';
    
    try {
        const appointments = await HttpClient.get('/appointment/overdue');
        displayAppointments(appointments);
    } catch (error) {
        console.error('加载逾期预约失败:', error);
        UI.showMessage('加载逾期预约失败', 'danger');
    }
}

/**
 * 显示预约列表
 */
function displayAppointments(data) {
    const appointments = normalizeAppointmentList(data);
    const tbody = document.getElementById('appointmentTableBody');
    tbody.innerHTML = '';
    
    if (!appointments || appointments.length === 0) {
        const message = currentMode === 'overdue' ? '暂无逾期预约' : '暂无预约记录，点击"创建预约"按钮创建';
        tbody.innerHTML = `
            <tr>
                <td colspan="6" style="text-align: center; padding: 40px; color: #999;">
                    <i class="fas fa-calendar-times" style="font-size: 48px; margin-bottom: 10px; display: block;"></i>
                    ${message}
                </td>
            </tr>
        `;
        return;
    }
    
    appointments.forEach(appointment => {
        const row = document.createElement('tr');
        
        // 判断是否可以取消（只有待接种状态才能取消，状态码：1=待接种）
        const canCancel = appointment.appointmentStatus === 1;
        const cancelButton = canCancel ? 
            `<button class="btn btn-danger btn-sm" onclick="handleCancelAppointment(${appointment.id})">
                <i class="fas fa-times"></i> 取消预约
            </button>` : 
            '<span style="color: #999;">-</span>';
        
        row.innerHTML = `
            <td>${appointment.personName || '-'}</td>
            <td>${appointment.vaccineName || '-'}</td>
            <td>${appointment.vaccinationSiteName || '-'}</td>
            <td>${Format.date(appointment.appointmentTime)}</td>
            <td>
                <span class="badge ${Format.appointmentStatusBadge(appointment.appointmentStatus)}">
                    ${Format.appointmentStatus(appointment.appointmentStatus)}
                </span>
            </td>
            <td>${cancelButton}</td>
        `;
        tbody.appendChild(row);
    });
}

/**
 * 显示创建预约模态框
 */
async function showCreateAppointmentModal() {
    document.getElementById('createAppointmentModal').classList.add('show');
    document.getElementById('createAppointmentForm').reset();
    
    // 加载预约人列表（自己+家属）
    await loadPersonList();
    
    // 加载疫苗列表
    await loadVaccineList();
}

/**
 * 关闭创建预约模态框
 */
function closeCreateAppointmentModal() {
    document.getElementById('createAppointmentModal').classList.remove('show');
}

/**
 * 加载预约人列表
 */
async function loadPersonList() {
    try {
        const userInfo = Auth.getUserInfo();
        personList = [];
        
        // 添加自己
        if (userInfo && userInfo.personId) {
            personList.push({
                id: userInfo.personId,
                name: userInfo.account || '本人'
            });
        }
        
        // 添加家属
        try {
        const families = await HttpClient.get('/family/list');
            if (families && Array.isArray(families) && families.length > 0) {
            families.forEach(family => {
                    if (family && family.personId) {
                personList.push({
                    id: family.personId,
                            name: family.name || '家属'
                        });
                    }
                });
            }
        } catch (familyError) {
            console.error('加载家属列表失败:', familyError);
            // 即使家属加载失败，也继续显示自己
        }
        
        // 填充下拉框
        const select = document.getElementById('appointmentPerson');
        if (select) {
        select.innerHTML = '<option value="">请选择预约人</option>';
            if (personList.length > 0) {
        personList.forEach(person => {
            const option = document.createElement('option');
            option.value = person.id;
            option.textContent = person.name;
            select.appendChild(option);
        });
            } else {
                // 如果没有可选的预约人，显示提示
                const option = document.createElement('option');
                option.value = '';
                option.textContent = '暂无可用预约人';
                option.disabled = true;
                select.appendChild(option);
            }
        }
    } catch (error) {
        console.error('加载预约人列表失败:', error);
        UI.showMessage('加载预约人列表失败', 'warning');
    }
}

/**
 * 加载疫苗列表
 */
async function loadVaccineList() {
    try {
        const pageData = await HttpClient.get('/vaccine/list?pageNum=1&pageSize=1000');
        // 处理分页数据
        if (pageData && pageData.records && Array.isArray(pageData.records)) {
            vaccineList = pageData.records;
        } else if (Array.isArray(pageData)) {
            // 如果直接返回数组
            vaccineList = pageData;
        } else {
            vaccineList = [];
        }

        const select = document.getElementById('appointmentVaccine');
        if (select) {
        select.innerHTML = '<option value="">请选择疫苗</option>';
            if (vaccineList.length > 0) {
        vaccineList.forEach(vaccine => {
                    if (vaccine && vaccine.id) {
            const option = document.createElement('option');
            option.value = vaccine.id;
                        option.textContent = `${vaccine.name || '未知疫苗'} - ${Format.vaccineType(vaccine.type)}`;
            select.appendChild(option);
                    }
        });
            } else {
                // 如果没有疫苗，显示提示
                const option = document.createElement('option');
                option.value = '';
                option.textContent = '暂无可用疫苗';
                option.disabled = true;
                select.appendChild(option);
            }
        }
    } catch (error) {
        console.error('加载疫苗列表失败:', error);
        UI.showMessage('加载疫苗列表失败: ' + (error.message || '未知错误'), 'warning');
        const select = document.getElementById('appointmentVaccine');
        if (select) {
            select.innerHTML = '<option value="">加载失败</option>';
        }
    }
}

/**
 * 加载接种点列表
 */
async function loadVaccinationSites() {
    const vaccineId = document.getElementById('appointmentVaccine').value;
    const siteSelect = document.getElementById('appointmentSite');
    const stockInfo = document.getElementById('stockInfo');
    
    if (!vaccineId) {
        siteSelect.innerHTML = '<option value="">请先选择疫苗</option>';
        stockInfo.textContent = '';
        return;
    }
    
    try {
        const sites = await HttpClient.get('/vaccinationsite/list');
        siteList = sites || [];
        
        siteSelect.innerHTML = '<option value="">请选择接种点</option>';
        siteList.forEach(site => {
            const option = document.createElement('option');
            option.value = site.id;
            option.textContent = `${site.name} - ${site.address}`;
            siteSelect.appendChild(option);
        });
        
        stockInfo.textContent = '请选择接种点查看库存信息';
    } catch (error) {
        console.error('加载接种点列表失败:', error);
        siteSelect.innerHTML = '<option value="">加载失败</option>';
    }
}

/**
 * 处理创建预约
 */
async function handleCreateAppointment() {
    const personId = document.getElementById('appointmentPerson').value;
    const vaccineId = document.getElementById('appointmentVaccine').value;
    const siteId = document.getElementById('appointmentSite').value;
    const appointmentTime = document.getElementById('appointmentTime').value;
    
    // 表单验证
    if (!personId) {
        UI.showMessage('请选择预约人', 'warning');
        return;
    }
    
    if (!vaccineId) {
        UI.showMessage('请选择疫苗', 'warning');
        return;
    }
    
    if (!siteId) {
        UI.showMessage('请选择接种点', 'warning');
        return;
    }
    
    if (!appointmentTime) {
        UI.showMessage('请选择预约日期', 'warning');
        return;
    }

    // 验证预约日期是否为未来日期（只比较日期部分，不比较时间）
    const selectedDate = new Date(appointmentTime);
    const today = new Date();
    today.setHours(0, 0, 0, 0); // 重置时间为00:00:00
    selectedDate.setHours(0, 0, 0, 0); // 重置时间为00:00:00

    if (selectedDate < today) {
        UI.showMessage('预约日期不能早于今天', 'warning');
        return;
    }
    
    try {
        const data = {
            personId: parseInt(personId),
            vaccineId: parseInt(vaccineId),
            vaccinationSiteId: parseInt(siteId),
            appointmentTime: appointmentTime
        };
        
        await HttpClient.post('/appointment', data);
        
        UI.showMessage('创建预约成功', 'success');
        closeCreateAppointmentModal();
        
        // 重新加载预约列表
        await loadAllAppointments();
    } catch (error) {
        console.error('创建预约失败:', error);
        
        // 检查是否是疫苗库存不足的错误
        let errorMessage = error.message || '创建预约失败';
        
        // 检查错误码（3003 = 疫苗库存不足）
        if (error.code === 3003 || errorMessage.includes('疫苗库存不足') || errorMessage.includes('3003')) {
            errorMessage = '该疫苗数量不足，请选择别的接种点';
        } else if (error.msg && (error.msg.includes('疫苗库存不足') || error.code === 3003)) {
            errorMessage = '该疫苗数量不足，请选择别的接种点';
        } else if (errorMessage.includes('服务器响应格式错误')) {
            // 如果显示服务器格式错误，可能是错误信息没有正确解析
            // 尝试从错误对象中提取更详细的信息
            if (error.code === 3003 || error.msg?.includes('库存不足')) {
                errorMessage = '该疫苗数量不足，请选择别的接种点';
            } else if (error.msg) {
                errorMessage = error.msg;
            }
        }
        
        UI.showMessage(errorMessage, 'danger');
    }
}

/**
 * 处理取消预约
 */
async function handleCancelAppointment(appointmentId) {
    UI.confirm('确定要取消此预约吗？取消后将无法恢复。', async () => {
        try {
            await HttpClient.put(`/appointment/${appointmentId}/cancel`);
            
            UI.showMessage('取消预约成功', 'success');
            
            // 直接从UI中移除该预约记录，不重新加载
            const tbody = document.getElementById('appointmentTableBody');
            if (tbody) {
                const rows = tbody.querySelectorAll('tr');
                rows.forEach(row => {
                    const cancelButton = row.querySelector(`button[onclick*="${appointmentId}"]`);
                    if (cancelButton) {
                        row.remove();
                    }
                });
                
                // 如果列表为空，显示提示
                if (tbody.children.length === 0) {
                    const message = currentMode === 'overdue' ? '暂无逾期预约' : '暂无预约记录，点击"创建预约"按钮创建';
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="6" style="text-align: center; padding: 40px; color: #999;">
                                <i class="fas fa-calendar-times" style="font-size: 48px; margin-bottom: 10px; display: block;"></i>
                                ${message}
                            </td>
                        </tr>
                    `;
                }
            }
        } catch (error) {
            console.error('取消预约失败:', error);
            UI.showMessage(error.message || '取消预约失败', 'danger');
        }
    });
}

/**
 * 设置默认预约日期为明天
 */
function setDefaultAppointmentTime() {
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);

    const year = tomorrow.getFullYear();
    const month = String(tomorrow.getMonth() + 1).padStart(2, '0');
    const day = String(tomorrow.getDate()).padStart(2, '0');

    // 日期格式：yyyy-MM-dd
    const defaultDate = `${year}-${month}-${day}`;
    document.getElementById('appointmentTime').value = defaultDate;
}

/**
 * 退出登录
 */
function handleLogout() {
    UI.confirm('确定要退出登录吗？', () => {
        Auth.logout();
    });
}

